package com.longe.netty.tcp.answer;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.UUID;

public class NettyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    /**
     * 异常
     *
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //关闭通道
        ctx.close();
    }

    /**
     * 读取信息
     *
     * @param ctx
     * @param msg
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) {

        //接收到数据并处理
        try {
            int len = msg.getLen();
            byte[] content = msg.getContent();

            System.err.println("长度 = " + len);
            System.err.println("内容 = " + new String(content, Charset.forName("utf-8")));
            System.err.println("服务器接收到消息包数量=" + (++this.count));

            //回复消息
            byte[] responseContent = UUID.randomUUID().toString().getBytes("utf-8");
            int responseLen = responseContent.length;
            //构建一个协议包
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setLen(responseLen);
            messageProtocol.setContent(responseContent);

            ctx.writeAndFlush(messageProtocol);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
}
